/**
 * 模型关联
 * @module models/index
 */

const User = require('./User');
const Category = require('./Category');
const Article = require('./Article');
const Comment = require('./Comment');
const Message = require('./Message');
const { sequelize } = require('../config/database');

// 文章与分类的关联关系
Article.belongsTo(Category, { foreignKey: 'categoryId', as: 'category' });
Category.hasMany(Article, { foreignKey: 'categoryId', as: 'articles' });

// 文章与评论的关联关系
Article.hasMany(Comment, { foreignKey: 'articleId', as: 'comments' });
Comment.belongsTo(Article, { foreignKey: 'articleId', as: 'article' });

/**
 * 初始化数据库
 * @param {boolean} force - 是否强制重建表
 * @returns {Promise<void>}
 */
const initDatabase = async (force = false) => {
  try {
    await sequelize.sync({ force });
    console.log('数据库同步完成');
    
    // 如果是强制重建，创建默认管理员账户
    if (force) {
      await createDefaultAdmin();
    }
  } catch (error) {
    console.error('数据库同步失败:', error);
    process.exit(1);
  }
};

/**
 * 创建默认管理员账户
 * @returns {Promise<void>}
 */
const createDefaultAdmin = async () => {
  try {
    await User.create({
      username: 'admin',
      password: 'admin123',
      email: 'admin@example.com',
      role: 'admin'
    });
    console.log('默认管理员账户创建成功');
  } catch (error) {
    console.error('默认管理员账户创建失败:', error);
  }
};

module.exports = {
  User,
  Category,
  Article,
  Comment,
  Message,
  sequelize,
  initDatabase
}; 